package com.soft.mainsite.component.shiro.realm;

import com.soft.mainsite.mybatis.model.TSysUser;
import com.soft.mainsite.module.web.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * Description:AdminRealm
 *
 * @author Jin
 * @create 2017-05-18
 **/
@Slf4j
@Component
public class AdminRealm extends AuthorizingRealm {

    @Autowired
	@Lazy
	private SysUserService userService;


	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		// 根据用户名查询用户的权限列表，并将权限名称提供给info
		info.setStringPermissions(userService.findSysUserPermissionsByUsername(username));
		// 根据用户名查询用户的角色列表，并将角色名称提供给info
		info.setRoles(userService.findSysUserRolesByUserame(username));
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username= (String) token.getPrincipal();
		// 根据用户名查询系统用户，先判断是否存在此用户，再判断用户是否已注销
		TSysUser user = userService.findSysUserByUsername(username);
		if (user == null) {
			throw new UnknownAccountException();
		}
		if (!user.getStatus()){
			throw new LockedAccountException();
		}
		log.info("user : ["+user .toString() + "]");
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
		return info;
	}

}